from flask import Blueprint,request,json,jsonify
from db import db1
import os,re,random,time
import requests
import datetime
bp_course=Blueprint('course',__name__)
def getdata():
    data=request.data
    if data:
        data=json.loads(data)
    else:
        data=request.form
@bp_course.route('/test',methods=['POST','GET','PUT','DELETE'])
def test():
    if request.method=='POST':
        data=request.data
        if data:
            data=json.loads(data)
        else:
            data=request.form
        sql="insert into test values(0,%d,'%s','%s','%s',%d)"%(int(data['total']),data['name'],data['start'],data['end'],int(data['state']))
        db1.insert(sql)
        return 'ok'
    elif request.method=='DELETE':
        id=request.args.get('id')
        sql="delete from test where id =%d"%(int(id))
        res=db1.insert(sql)
        return jsonify({'code':200})
    elif request.method=='PUT':
        data=request.data
        if data:
            data=json.loads(data)
        else:
            data=request.form
        sql="update test set total=%d,name='%s',starttime='%s',endtime='%s',state=%d where id=%d"%(int(data['total']),data['name'],data['start'],data['end'],int(data['state']),int(data['id']))
        res=db1.insert(sql)
        return jsonify({'code':200})
    else:
        id=request.args.get('id')
        sql="select * from test where id =%d"%(int(id))
        res=db1.find(sql)
        return jsonify({'code':200,'test':res})

from utils.myfile import myfile
@bp_course.route('/upload',methods=['POST'])
def upload():
    file=request.files['file']
    myfile.file_mkdir(2)
    file.save(os.path.join('./static/upload/2',file.filename))
    return 'ok'

@bp_course.route('/scenic',methods=['POST','GET'])
def scenic():
    if request.method=='POST':
        data=request.data
        if data:
            data=json.loads(data)
        else:
            data=request.form
        print(data)
        sql="insert into scenic(title,price,typeid) values('%s',%.2f,%d)"%(data['title'],float(data['price']),int(data['typeid']))
        db1.insert(sql)
        print(sql)
        print('添加成功')
        sql1="select id from scenic where title='%s'"%(data['title'])
        res=db1.find(sql1)
        file=request.files['file']
        myfile.file_mkdir(str(res['id']))
        file.save(os.path.join('./static/upload/'+str(res['id']),file.filename))
        sql2="update scenic set pic='%s' where id=%d"%('/static/upload/'+str(res['id']+"/"+file.filename),int(res['id']))
        db1.insert(sql2)
        return jsonify({'code':200})
    else:
        sql="select * from scenic"
        res=db1.find(sql)
        return jsonify({'code':200,'list':res})

@bp_course.route('cate')
def cate():
    sql="select * from yptype"
    res=db1.findall(sql)
    return jsonify({'code':200,'list':res})

@bp_course.route('record')
def record():
    id=request.args.get('typeid')
    if id=='0':
        sql="select * from record"
    else:
        sql="select * from record where id=%d"%(int(id))
    res=db1.findall(sql)
    list=[]
    for i in res:
        dict={'id':i['id'],'stime':datetime.datetime.strftime(i['stime'],'%Y-%m-%d'),'etime':datetime.datetime.strftime(i['etime'],'%Y-%m-%d'),'money':float(i['money'])}
        list.append(dict)
    return jsonify({'code':200,'list':list})

@bp_course.route('order',methods=['GET','PUT'])
def order():
    if request.method=='PUT':
        id=request.args.get('id')
        sql="select * from orders where id=%d"%(int(id))
        res=db1.find(sql)
        status=2
        if int(res['status'])==2:
            status=1
        sql1="update orders set status=%d where id=%d"%(status,int(id))
        db1.insert(sql1)
        return jsonify({"code":200})
    else:
        page=int(request.args.get('page'))
        page_size=int(request.args.get('page_size'))
        start=(page-1)*page_size
        sql="select * from orders limit %d,%d"%(start,page_size)
        res=db1.findall(sql)
        sql1="select count(id) from orders"
        res1=db1.find(sql1)
        return jsonify({'code':200,'list':res,'total':res1['count(id)']})

@bp_course.route('detail',methods=['POST'])
def detail():
    data=request.data
    if data:
        data=json.loads(data)
    else:
        data=request.form
    sql="insert into goods(name,price,count,order_id) values('%s',%.2f,%d,%d)"%(data['name'],float(data['price']),int(data['count']),int(data['order_id']))
    db1.insert(sql)
    return jsonify({'code':200})

@bp_course.route('homework1',methods=['POST','GET','PUT','DELETE'])
def homework1():
    if request.method=='POST':
        data=request.data
        if data:
            data=json.loads(data)
        else:
            data=request.form
        sql="insert into cate(name) values('%s')"%(data['name'])
        db1.insert(sql)
        return jsonify({'code':200})
    elif request.method=='DELETE':
        id=int(request.args.get('id'))
        sql="delete from cate where id=%d"%(id)
        db1.delete(sql)
        return jsonify({'code':200})
    elif request.method=='PUT':
        # data=request.data
        # if data:
        #     data=json.loads(data)
        # else:
        #     data=request.form
        id=int(request.args.get('id'))
        # sql1="update cate set name=%s"%(data['name'])
        # res=db1.update(sql1)
        sql="select * from cate where id=%d"%(id)
        res=db1.find(sql)
        return jsonify({'code': 200,'list':res})
    else:
        sql="select * from cate"
        res=db1.findall(sql)
        return jsonify({'code':200,'list':res})

@bp_course.route('sendmoney')
def sendmoney():
    money=request.args.get('money')
    if not money:
        return jsonify({'code':201,'mes':'请输入金额'})
    else:
        try:
            money=float(money)
        except:
            return jsonify({'code':202,'mes':'请输入正确格式'})
    if money<0.01:
        return jsonify({'code':203,'mes':'红包金额最小为0.01'})
    elif money>200:
        return jsonify({'code':204,'mes':'红包金额最大为200'})
    else:
        return jsonify({'code': 200,'mes':'格式正确！金额大小符合要求！'})

@bp_course.route('test_record',methods=['POST'])
def test_record():
    if request.method=='POST':
        data=getdata()
        sql="insert into test_record(name,url,method,params,result) values('%s','%s','%s','%s','%s')"%(data['name'],data['url'],data['method'],data['params'],data['result'])
        print(sql)
        db1.insert(sql)
        return jsonify({'code':200})

#获取手机号
        #判断有效性
        #判断1分钟
        #生成验证码发送
        #发送成功写入记录表
        #返回结果
@bp_course.route('sendsms',methods=['POST'])
def sendsms():
    if request.method=='POST':
        data=request.data
        if data:
            data=json.loads(data)
        else:
            data=request.form
        # try:
        #     mobile=data['mobile']
        # except:
        #     return jsonify({'code':201,'mes':'不能为空'})
        mobile=data['mobile']
        if not mobile:
            return jsonify({'code':201,'mes':'不能为空'})
        res=re.match('^1[3-9]\d{9}$',mobile)
        print(res.group())
        if not res:
            return jsonify({'mes'})
        sql="select stime from record where mobile ='%s' order by id desc limit 1"%(str(mobile))
        record=db1.find(sql)
        if record:
            seconds=int(time.time())-int(record['stime'])
            if seconds<60:
                return jsonify({'code':205,'mes':'发送频繁,请稍后再试'})
        code=random.randint(100000,999999)
        sql2="insert into record(mobile,code,stime) values('%s','%s','%s')"%(mobile,int(code),int(time.time()))
        db1.insert(sql2)
        print(sql2)
        return jsonify({'code':200,'mes':'发送成功','sms':int(code)})


@bp_course.route('login',methods=['POST'])
def login():
    data=request.data
    if data:
        data=json.loads(data)
    else:
        data=request.form
    sql="select code,stime from record where mobile = '%s'"%data['mobile']
    res=db1.find(sql)
    if int(time.time())-int(res['stime'])>60:
        return jsonify({'code':201,'mes':'验证码过期'})
    if res['code']==int(data['code']):
        sql1="select id from user where mobile ='%s'"%data['mobile']
        user=db1.find(sql1)
        if user:
            return jsonify({'code':200,'mes':'登陆成功','userid':user['id']})
        sql2="insert into user(mobile) values('%s')"%data['mobile']
        db1.insert(sql2)
        user2=db1.find(sql1)
        return jsonify({'code':203,'mes':'注册成功','userid':user2['id']})
    else:
        return jsonify({'code':202,'mes':'验证码不匹配'})


@bp_course.route('search_add',methods=['POST'])
def search_add():
    data=request.data
    if data:
        data=json.loads(data)
    else:
        data=request.form
    sql="insert into goods(title,content) values('%s','%s')"%(data['title'],data['content'])
    db1.insert(sql)
    sql1="select * from goods"
    res=db1.findall(sql1)
    return jsonify({'code':200,'mes':'添加成功','list':res})

@bp_course.route('search',methods=['POST'])
def search():
    title=request.args.get('title')
    title=title.strip()
    print(title)
    if not title:
        return jsonify({'code':201,'mes':'标题不符合'})
    if 1<len(title)<10:
        ip=request.remote_addr
        print(ip)
        sql="insert into search(title,ip) values('%s','%s')"%(title,ip)
        sql1="select * from goods where title like '%"+title+"%'"
        db1.insert(sql)
        res=db1.findall(sql1)
        print(res)
        return jsonify({'code':200,'list':res})
    else:
        return jsonify({'code':202,'mes':'格式错误'})

@bp_course.route('login',methods=['POST','GET','PUT','DELETE'])
def login():
    data=request.data
    if data:.+102
        data=json.loads(data)
    else:
        data=request.form
    username=data['username']
    password=data['password']
    sql="select * from user where user='%s'"%username
    res=db1.find(sql)
    username1=res['username']
    password1=res['password']
    id=res['id']
    if username1==username:
        if password==password1:
            return jsonify({'code':200,'mes':'添加成功','userid':res['id']})
        else:
            return jsonify({'code':201,'mes':'密码错误，重新输入'})
    else:
        return jsonify({'code':202,'mes':'该用户不存在'})
    if []













